//
//  KDKeywordGroupEditController.m
//  PublicSentimentMonitorSystem
//
//  Created by 魏强 on 15/11/20.
//  Copyright © 2015年 魏强. All rights reserved.
//

#import "KDKeywordGroupEditController.h"
#import "KDMainwordAddView.h"
#import "KDMainWordAddViewModel.h"
#import "UIViewController+BackButtonHandler.h"
#import "KDNoticeView.h"
#import "KDEditeCellModel.h"
#import "SVProgressHUD.h"
#define CELL_HEIGHT 40
#define MAX_NUM 4
#define NOTICE_LINE_HEIGHT 21

@interface KDKeywordGroupEditController ()<KDMainwordAddViewDelegate,BackButtonHandlerProtocol>
/**
 *  控制器底部的scrollView
 */
@property (nonatomic, strong) UIScrollView *underScrollView;
/**
 *  所有关键词组中最下面的那个词组
 */
@property (nonatomic, weak) KDMainwordAddView *lowestView;
/**
 *  添加关键词组按钮
 */
@property (nonatomic, weak) UIButton *addBtn;
/**
 *  传入的总关键词组
 */
@property (nonatomic, strong) NSArray * infoArr;
/**
 *  当前的关键词组
 */
@property (nonatomic, strong) NSArray *cureentGroupArr;
/**
 *  一个自增的mainView标签
 */
@property (nonatomic, assign) NSInteger mainViewTag;
/**
 *  keyoard的高度
 */
@property (nonatomic, assign) CGFloat keyboardH;
@end

@implementation KDKeywordGroupEditController
#pragma mark - 版面设置区
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpNavBar];
    [self setUpScrollView];
    [self getKeywordGroup];
    [self setUpAddBtn];
    //添加手势
    UITapGestureRecognizer *hide = [[UITapGestureRecognizer alloc] init];
    [hide addTarget:self action:@selector(hideTheKeyBoard)];
    [self.view addGestureRecognizer:hide];
    // Do any additional setup after loading the view from its nib.
}
/**
 *  设置控制器底部scrollView
 */
- (void)setUpScrollView{
    //加一个挡板
    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
    view.backgroundColor = [UIColor clearColor];
    [self.view addSubview:view];
    //初始化underScrollView
    UIScrollView *underScrollView = [[UIScrollView alloc]init];
    self.underScrollView = underScrollView;
    underScrollView.frame = CGRectMake(0, 0, screenW, screenH);
    underScrollView.contentSize = CGSizeMake(1, screenH);
    underScrollView.backgroundColor = BackGroundColor;
    underScrollView.showsHorizontalScrollIndicator = NO;
    underScrollView.showsVerticalScrollIndicator = YES;
    [self.view addSubview:self.underScrollView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
/**
 *  当那边传值时，这边就接收处理
 */
- (void)setKeywordGroupstr:(NSString *)keywordGroupstr{
    _keywordGroupstr = keywordGroupstr;
    NSMutableArray *tempArr = [NSMutableArray array];
    if (keywordGroupstr.length == 0) {//传进来的是空
    }else{
        NSArray *arr = [keywordGroupstr componentsSeparatedByString:@"$"];
        
        for (int i = 0; i < arr.count; i++) {
            NSMutableArray *tempSubArr = [NSMutableArray array];
            NSString * str = arr[i];
            if (!str.length) {
                break;
            }
            NSArray *cellNameArr = [str componentsSeparatedByString:@","];//获取单个关键词组
            for (NSString *str1 in cellNameArr) {
                KDEditeCellModel *model = [[KDEditeCellModel alloc]init];
                model.name = str1;
                //        model.num = i;
                [tempSubArr addObject:model];
            }
            //创建mainView的模型，装进infoArr
            KDMainWordAddViewModel *model = [[KDMainWordAddViewModel alloc]init];
            model.infoArr = tempSubArr;
            model.index = self.mainViewTag;
            model.wordTfPlaceHolder = @"添加关键词";
            model.single = NO;
            [tempArr addObject:model];
            self.mainViewTag++;
        }

    }
        self.infoArr = tempArr;
}
- (void)setInfoArr:(NSArray *)infoArr{
    _infoArr = infoArr;
    if (infoArr.count >0) {
    }
    for (KDMainWordAddViewModel *model in self.infoArr) {//遍历自己的数据库
        if (!model.infoArr.count) {//如果前面的这几组数据中有空的，就不让他添加组
            self.addBtn.enabled = NO;
            return;
        }

    }
    self.addBtn.enabled = YES;
}
/**
 *  获取现有的所有的关键词组
 */
- (void)getKeywordGroup{
    NSInteger i= 0;
    for (KDMainWordAddViewModel *model in self.infoArr) {
        self.cureentGroupArr = model.infoArr;
        [self addKeywordGroupWithIndex:i];
        i++;
    }
}
/**
 *  添加一组关键词组
 */
- (void)addKeywordGroupWithIndex:(NSInteger)index{
    KDMainwordAddView *mainView = [KDMainwordAddView wordView];
    mainView.model = self.infoArr[index];
    NSInteger count = (mainView.model.infoArr.count > 4) ? MAX_NUM : mainView.model.infoArr.count;
    mainView.frame = CGRectMake(0,CGRectGetMaxY(self.lowestView.frame) + 10, screenW, CELL_HEIGHT * (count +1));
//    KDLog(@"%@,\n self.lowestView = %@",NSStringFromCGRect(mainView.frame), NSStringFromCGRect(self.lowestView.frame));
    mainView.delegate = self;

    [self.underScrollView addSubview:mainView];
    self.lowestView = mainView;
}
- (void)setUpNavBar{
    self.navigationController.navigationBar.hidden = NO;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"leftArrow"] style:UIBarButtonItemStylePlain target:self action:@selector(backViewClick)];
}
/**
 *  设置添加关键词组按钮
 */
- (void)setUpAddBtn{
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    addBtn.frame = CGRectMake(0, CGRectGetMaxY(self.lowestView.frame)+10, screenW, 44);
    [addBtn setImage:[UIImage imageNamed:@"添加"] forState:UIControlStateNormal];
    [addBtn setImage:[UIImage imageNamed:@"默认添加"] forState:UIControlStateDisabled];
    [addBtn addTarget:self action:@selector(addBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    addBtn.backgroundColor = [UIColor whiteColor];
    [addBtn setTitleColor:KDColor forState:UIControlStateNormal];
    self.addBtn = addBtn;
    [self.underScrollView addSubview:addBtn];
    self.underScrollView.contentSize = CGSizeMake(screenW, CGRectGetMaxY(self.addBtn.frame)+ 74) ;
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - 事件点击区
/**
 *  添加关键词组的按钮被点击了
 */
- (void)addBtnClick:(UIButton *)addBtn{
    if (self.infoArr.count >= 5) {//最多加5组
        [SVProgressHUD showInfoWithStatus:@"总数已超过5个，不能再添加！" maskType:SVProgressHUDMaskTypeGradient];
        return;
    }
    NSMutableArray *tempArr = [NSMutableArray arrayWithArray:self.infoArr];
    KDMainWordAddViewModel *model = [[KDMainWordAddViewModel alloc]init];
    model.infoArr = nil;
    model.index = self.mainViewTag;
    self.mainViewTag++;
    model.wordTfPlaceHolder = @"添加关键词";
    model.single = NO;
    [tempArr addObject:model];
    self.infoArr = tempArr;
//    self.cureentGroupArr = nil;//添加一组空的关键词组
    [self addKeywordGroupWithIndex:self.infoArr.count -1];
    self.addBtn.y = CGRectGetMaxY(self.lowestView.frame)+10;
    self.underScrollView.contentSize = CGSizeMake(screenW, CGRectGetMaxY(self.addBtn.frame)+ 74) ;
//    KDLog(@"%@", NSStringFromCGSize(self.underScrollView.contentSize));
}

/**
 *  返回按钮被点击了
 */
- (void)backViewClick{
    if (_delegate && [_delegate respondsToSelector:@selector(groupEditController:finishedEditWith:)]) {
        NSMutableString *str = [NSMutableString string] ;
        if (!self.infoArr.count) {//如果关键词组是空的
        [_delegate groupEditController:self finishedEditWith:str];
        [self.navigationController popViewControllerAnimated:YES];
            return ;
        }
        for (KDMainWordAddViewModel *model in self.infoArr) {//遍历自己的数据库
            if (model.infoArr.count)
            {//如果存在数据
                for (KDEditeCellModel *editeCellModel in model.infoArr) {
                    NSString *word = [NSString stringWithFormat:@"%@,",editeCellModel.name];
                    [str appendFormat:@"%@", word];
                }
                [str deleteCharactersInRange:NSMakeRange(str.length -1, 1)];
                [str appendFormat:@"$"];
            }
        }
        if (!str.length) {//
            [_delegate groupEditController:self finishedEditWith:str];
            [self.navigationController popViewControllerAnimated:YES];
            return ;
        }
        [str deleteCharactersInRange:NSMakeRange(str.length -1, 1)];
        [_delegate groupEditController:self finishedEditWith:str];
    }
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - KDMainwordAddViewDelegate
/**
 *  删除按钮或者添加按钮被点击了
 */
- (void)KDMainwordAddView:(KDMainwordAddView *)mainWordView HeightChangeWithIfAdd:(BOOL)add AndHeight:(CGFloat)height{
    if (add) {//是添加
        for (UIView *view in self.underScrollView.subviews) {
            if (view.y > mainWordView.y) {
                view.y += height;
            }
        }
    }else{//是删除
        for (UIView *view in self.underScrollView.subviews) {
            if (view.y > mainWordView.y) {
                view.y -= height;
            }
        }
    }
    self.underScrollView.contentSize = CGSizeMake(screenW, CGRectGetMaxY(self.addBtn.frame)+ 74) ;
    NSMutableArray *tempArr = [NSMutableArray arrayWithArray:self.infoArr];
    //随着变化更新infoArr里面的数据
    int i=0;
    for (KDMainWordAddViewModel *model in self.infoArr) {
        if (model.index == mainWordView.model.index) {
            [tempArr replaceObjectAtIndex:i withObject:mainWordView.model];
        }
        i++;
    }
    self.infoArr = tempArr;
}

- (void)wordTfCoverdByKeyboardWithKDMainwordAddView:(KDMainwordAddView *)mainWordView{
    [UIView animateWithDuration:0.25 animations:^{
        self.view.y = -self.keyboardH + 64;
        [self.view layoutIfNeeded];
    }];
}
#pragma mark - BackButtonHandlerProtocol

#pragma mark - 通知
/**
 *  键盘将要打开时的通知
 */
- (void)keyboardWillShow:(NSNotification *)notif{
    CGRect kbBounds = [notif.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    self.keyboardH = kbBounds.size.height;
}
/**
 *  键盘将要收起时的通知
 */
- (void)keyboardWillHide:(NSNotification *)notif{
    self.view.y = 64;
}
#pragma mark - 隐藏键盘
- (void)hideTheKeyBoard
{
    [self.view endEditing:YES];
}

@end
